package cn.tedu.csmall.sso.service.impl;

import cn.tedu.csmall.commons.pojo.admin.vo.AdminLoginVO;
import cn.tedu.csmall.sso.mapper.AdminMapper;
import cn.tedu.csmall.sso.utils.AdminUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.info("Spring Security自动根据用户【{}】查询用户信息",s);
        AdminLoginVO adminLoginVO = adminMapper.selectUserDetail(s);
        //判断查询结果是否有效
        if (adminLoginVO!=null) {
            log.info("查询到的管理员的用户信息为：",adminLoginVO);
//            UserDetails userDetails = User.builder()//利用User进行属性构建
//                    .username(adminLoginVO.getUsername())//用户名
//                    .password(adminLoginVO.getPassword())//密码
//                    .disabled(false)//账号是否禁用
//                    .accountLocked(false)//账号是否锁定
//                    .accountExpired(false)//账号是否过期
//                    .authorities("忽略")//账号的权限信息
//                    .build();
            //那permissions集合中搞得属性赋值到 Collection<? extends GrantedAuthority>
            List<String> permissions = adminLoginVO.getPermissions();
            List<SimpleGrantedAuthority> authorities=new ArrayList<>();
            for (String permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission));
            }
            AdminUserDetails userDetails=new AdminUserDetails(
                    adminLoginVO.getId(),
                    adminLoginVO.getUsername(),
                    adminLoginVO.getPassword(),
                    adminLoginVO.getEnable()==1,
                    authorities
            );
            log.info("userDetails：{}",userDetails);//密码被隐藏
            return userDetails;
        }
        return null;
    }
}
